package main

import (
	"awesomeProject/common"
	"awesomeProject/controller"
	"awesomeProject/repositories"
	"awesomeProject/service"
	"context"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"github.com/sirupsen/logrus"
)

func main() {
	app := iris.New()
	app.Logger().SetLevel("debug")

	template := iris.HTML("./web/views", ".html").Layout("shared/layout.html").Reload(true)
	app.RegisterView(template)
	app.OnAnyErrorCode(notFound)

	// 连接数据库
	conn, err := common.NewMysqlConn()
	if err != nil {
		panic(err)
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// 注册product控制器
	productRepo := repositories.NewProdctManger("product", conn)
	productService := service.MewProductService(productRepo)
	productParty := app.Party("/product")
	product := mvc.New(productParty)
	product.Register(ctx, productService)
	product.Handle(new(controller.ProductController))

	// 启动
	err = app.Run(
		iris.Addr("localhost:8080"),
		iris.WithoutServerError(iris.ErrServerClosed),
		iris.WithOptimizations,
	)
	if err != nil {
		return
	}
}

func notFound(ctx iris.Context) {
	err := ctx.View(`shared/404.html`)
	logrus.Error(err)
}
